package com.ea.modular.service.sys;

import java.io.IOException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.ea.common.parent.service.CrudService;
import com.ea.common.utils.FileUtil;

import com.ea.modular.model.sys.File;

import com.ea.modular.dao.sys.FileDao;
/**
 * FileService实现类
 * @author jun
 *
 */
@Service
@Transactional(readOnly=true)
public class FileService  extends CrudService<FileDao,File>{

	private static final Logger log = LoggerFactory.getLogger("adminLogger");
	@Value("${files.path}")
	private String filesPath;

	@Autowired
	private FileDao fileDao;

	@Transactional(readOnly=false)
	public File upload(MultipartFile file) throws IOException {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("缺少后缀名");
		}

		String md5 = FileUtil.fileMd5(file.getInputStream());
      

		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String pathname = FileUtil.getPath() + md5 + fileOrigName;
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);

		long size = file.getSize();
		String contentType = file.getContentType();

	    File fileInfo = new File();
	
		fileInfo.setContentType(contentType);

		fileInfo.setSize(size);
		fileInfo.setPath(fullPath);
		fileInfo.setUrl(pathname);
		fileInfo.setType(contentType.startsWith("image/") ? "1" : "0");



		fileInfo.preInsert();
		fileDao.insert(fileInfo);

		log.debug("上传文件{}", fullPath);

		return fileInfo;
	}

}
